package com.fc.campusapplicationsystem.service;

import com.fc.campusapplicationsystem.mapper.SuperuserMapper;
import com.fc.campusapplicationsystem.model.Superuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 贺哲
 * @2020-02-29 15:18
 */
@Service
public class SuperuserServiceImpl implements SuperuserService {

    @Autowired
    SuperuserMapper superuserMapper;

    @Override
    public Superuser superuserLogin(String username, String password) {
        return superuserMapper.selectOne(new Superuser().
                setSuperuserName(username).
                setSuperuserPassword(password));
    }

    @Override
    public List<Superuser> list(String key) {
        List<Superuser> superusers = new ArrayList<>();
        Example example = new Example(Superuser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isEmpty(key)) {
            superusers = superuserMapper.selectAll();
        } else {
            criteria.andLike("superuserName", "%" + key + "%");
            superusers = superuserMapper.selectByExample(example);
        }
        return superusers;
    }

    @Override
    public List<Superuser> listAll() {
        return superuserMapper.selectAll();
    }

    @Override
    public Integer add(Superuser superuser) {
        return superuserMapper.insertSelective(superuser);
    }

    @Override
    public Superuser getByType(Integer value) {
        Example example = new Example(Superuser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("superuserType",value);
        return superuserMapper.selectOneByExample(example);
    }

    @Override
    public Integer delete(Integer id) {
        return superuserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Integer update(Superuser superuser) {
        return superuserMapper.updateByPrimaryKey(superuser);
    }

    @Override
    public boolean checkUsername(Superuser superuser) {
        List<Superuser> superuserList = superuserMapper.selectAll();
        for (Superuser s : superuserList) {
            if (s.getSuperuserName().equals(superuser.getSuperuserName())){
                return false;
            }
        }
        return true;
    }
}
